<?php


namespace App\Common\Tools;

/**
 * 把一张表的数据关联进另一张表
 * Class JoinTableToList
 * @package App\Library
 */
class JoinTableToList
{
    public static function joinMany(array &$list, array $joinList, string $joinName, string $field, string $joinField = null)
    {

        $joinField = $joinField == null ? $field : $joinField;

        $fields = [];

        foreach ($joinList as $item) {

            $tdField = is_object($item) ? $item->$joinField : $item[$joinField];
            $fields[$tdField][] = $item;

            continue;

        }

        foreach ($list as &$vv) {
            is_object($vv) ? $vv->$joinName : $vv[$joinName] = is_array($vv) ? ($fields[$vv[$field]] ?? []) : ($fields[$vv->$field] ?? []);
        }
    }


    /**
     * joinOne
     * @param array $list
     * @param array $joinList
     * @param string $joinName
     * @param string $field
     * @param string|null $joinField
     * date:2021/7/5
     * time:10:02
     * auth：xyc
     */
    public static function joinOne(array &$list, array $joinList, string $joinName, string $field, string $joinField = null)
    {

        $joinField = $joinField == null ? $field : $joinField;
        $fields = [];

        foreach ($joinList as $item) {

            $tdField = is_object($item) ? $item->$joinField : $item[$joinField];
            $fields[$tdField] = $item;
            continue;

        }
        foreach ($list as &$vv) {
            is_object($vv) ? $vv->$joinName : $vv[$joinName] = is_array($vv) ? ($fields[$vv[$field]] ?? []) : ($fields[$vv->$field] ?? null);
        }

    }


    /**
     * join 自定义
     * @param array $list
     * @param array $joinList
     * @param callable $func1
     * @param callable $func2
     * date:2021/7/5
     * time:10:13
     * auth：xyc
     */
    public static function join(array &$list, array $joinList, callable $func1, callable $func2)
    {

        $fields = [];

        foreach ($joinList as $item) {
            $func1($fields, $list, $item);
        }

        foreach ($list as &$vv) {
            $func2($fields, $vv);
        }
    }


}